<?php
namespace app\home\controller;

use app\common\component\user\UserService;
use app\common\component\user_wallet\UserWalletService;
use app\common\component\user_wallet_log\UserWalletLogService;
use app\common\component\user_wallet_log\UserWalletLogValidate;

class User extends ControllerBase {
    public function index() {
    	return $this -> view -> fetch();
    }

    public function topUp() {
    	if(!getParam('TOP_UP_IS_OPEN')) {
    		echo '<meta charset="utf-8"><script>alert("充值功能已关闭!");window.location.href="/user/vip";</script>';exit;
    	}

    	if($this -> request -> isPost()) {
    		$this -> createUserWalletLog();
    	}

    	$resultUser = (new UserService) -> getUser();
    	if($resultUser['code'] != 0) {
    		echo '<meta charset="utf-8"><script>alert("账号不存在!");window.location.href="/user/vip";</script>';exit;
    	}

    	$this -> view -> assign('user', $resultUser['data']['user']);

    	$resultUserWallet = (new UserWalletService) -> getUserWallet();
    	$this -> view -> assign('user_wallet', $resultUserWallet['data']['user_wallet']);

    	return $this -> view -> fetch();
    }
    
    public function createUserWalletLog() {
    	$post = $this -> request -> post();

    	$resultUserWalletLogValidate = (new UserWalletLogValidate) -> create($post);
		if($resultUserWalletLogValidate['code'] !== 0) {
			echo '<meta charset="utf-8"><script>alert("' . $resultUserWalletLogValidate['message'] . '!");window.history.go(-1);</script>';exit;
		}

		$resultUser = \app\common\component\user\UserModel::get(['username' => $post['to_user_name']]);
		if(!$resultUser) {
			echo '<meta charset="utf-8"><script>alert("此' . $post['to_user_name'] . '用户不存在!");window.history.go(-1);</script>';exit;
		}

		$post['type'] = 1;
		$post['active'] = 1;
		$post['from_user_name'] = \think\Session::get('user_name');
		$resultUserWallet = (new UserWalletService) -> getUserWallet($resultUser['user_id']);
		$post['to_user_name_new_money'] = $resultUserWallet['data']['user_wallet'] -> money + $post['price'];
		$post['to_user_name_old_money'] = $resultUserWallet['data']['user_wallet'] -> money;
		$post['create_time'] = time();
		$post['voucher'] = uploadFile();
		$post['remark'] = '用户金钱充值';
		$post['is_state'] = 0;

		unset($post['file']);
    	$resultUserWalletLog = (new UserWalletLogService) -> create($post);
    	if($resultUserWalletLog['code'] !== 0) {
			echo '<meta charset="utf-8"><script>alert("' . $resultUserWalletLog['message'] . '!");window.history.go(-1);</script>';exit;
		}
		echo '<meta charset="utf-8"><script>alert("' . $resultUserWalletLog['message'] . '!");window.location.href="/user/vip";</script>';exit;
    }
}